/*
	editstations.cpp

	Copyright (c) 2009 by Lms <lms.cze7@gmail.com>

 ***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************
*/

#include "editstations.h"
#include "ui_editstations.h"

#include "fmtunePlugin.h"

#include <QTreeView>
#include <QStandardItemModel>

EditStations::EditStations(QWidget *parent) :
    QDialog(parent),
    m_ui(new Ui::EditStations)
{
    m_ui->setupUi(this);
}

EditStations::~EditStations()
{
    delete m_ui;
}

void EditStations::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void EditStations::showEvent()
{
	QStringList labels;
	labels << tr("Format") << tr("URL");
	m_ui->treeStations->setHeaderLabels(labels);

	m_ui->toolButtonStationsAdd->setIcon( QIcon(":/icons/add.png") );
	m_ui->toolButtonStationsDelete->setIcon( QIcon(":/icons/delete.png") );
	m_ui->toolButtonStreamsAdd->setIcon( QIcon(":/icons/add.png") );
	m_ui->toolButtonStreamsDelete->setIcon( QIcon(":/icons/delete.png") );

	m_ui->toolButtonStationsUp->setIcon( QIcon(":/icons/up.png") );
	m_ui->toolButtonStationsDown->setIcon( QIcon(":/icons/down.png") );
	m_ui->toolButtonStreamsUp->setIcon( QIcon(":/icons/up.png") );
	m_ui->toolButtonStreamsDown->setIcon( QIcon(":/icons/down.png") );
	
	connect(m_ui->treeStations, SIGNAL( currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*) ) , this, SLOT(stationsChanged(QTreeWidgetItem*,QTreeWidgetItem*) ));
	connect(m_ui->treeStreams, SIGNAL( currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*) ) , this, SLOT(streamsChanged(QTreeWidgetItem*,QTreeWidgetItem*) ));
	connect(m_ui->pushButtonStationSave, SIGNAL( clicked() ) , this, SLOT( clickSave() ));

	connect(m_ui->toolButtonStationsAdd, SIGNAL( clicked() ) , this, SLOT( clickStationsAdd() ));
	connect(m_ui->toolButtonStationsDelete, SIGNAL( clicked() ) , this, SLOT( clickStationsDelete() ));
	connect(m_ui->toolButtonStreamsAdd, SIGNAL( clicked() ) , this, SLOT( clickStreamsAdd() ));
	connect(m_ui->toolButtonStreamsDelete, SIGNAL( clicked() ) , this, SLOT( clickStreamsDelete() ));

	connect(m_ui->toolButtonStationsUp, SIGNAL( clicked() ) , this, SLOT( clickStationsUp() ));
	connect(m_ui->toolButtonStationsDown, SIGNAL( clicked() ) , this, SLOT( clickStationsDown() ));
	connect(m_ui->toolButtonStreamsUp, SIGNAL( clicked() ) , this, SLOT( clickStreamsUp() ));
	connect(m_ui->toolButtonStreamsDown, SIGNAL( clicked() ) , this, SLOT( clickStreamsDown() ));

	connect(m_ui->pushButtonImport, SIGNAL( clicked() ) , this, SLOT( clickImport() ));
	connect(m_ui->pushButtonExport, SIGNAL( clicked() ) , this, SLOT( clickExport() ));

	m_ui->toolButtonStationsUp->setDisabled(true);
	m_ui->toolButtonStationsDown->setDisabled(true);
	m_ui->toolButtonStreamsUp->setDisabled(true);
	m_ui->toolButtonStreamsDown->setDisabled(true);

	//m_ui->pushButtonImport->setDisabled(true);
	//m_ui->pushButtonExport->setDisabled(true);

	showStations();
}

void EditStations::showStations()
{
	m_ui->treeStations->clear();
	QString sql;
	sql = "SELECT [id], [name] FROM Stations";
	QSqlQuery query(sql, sqldb.db);
	while (query.next()) {
		QTreeWidgetItem *item = new QTreeWidgetItem(m_ui->treeStations);
		item->setText(0, query.value(1).toString());
		item->setData(0,Qt::UserRole,QVariant(query.value(0).toString()));
	}
	query.finish();
}

void EditStations::showStreams()
{
	m_ui->treeStreams->clear();
	if (m_ui->treeStations->indexOfTopLevelItem(m_ui->treeStations->currentItem()) != -1 ) {
		QString sql;
		sql = QString("SELECT [id], [format], [url] FROM Streams WHERE stationid='%1'").arg( m_ui->treeStations->currentItem()->data(0,Qt::UserRole).toString() );
		QSqlQuery query(sql, sqldb.db);
		while (query.next()) {
			QTreeWidgetItem *item = new QTreeWidgetItem(m_ui->treeStreams);
			item->setText(0, query.value(1).toString());
			item->setText(1, query.value(2).toString());
			item->setData(0, Qt::UserRole, QVariant(query.value(0).toString()));
		}
		query.finish();
	}
}

void EditStations::stationsChanged(QTreeWidgetItem *current,QTreeWidgetItem *before)
{
	if (m_ui->treeStations->indexOfTopLevelItem(m_ui->treeStations->currentItem()) != -1 ) {
		qDebug() << "stationsChanged"<<m_ui->treeStations->indexOfTopLevelItem(current)<<current->data(0,Qt::UserRole).toString();

		QString sql;
		sql = QString("SELECT name, genre, language, image, url FROM Stations WHERE id='%1'").arg( current->data(0,Qt::UserRole).toString() );
		QSqlQuery query2(sql, sqldb.db);
		while (query2.next()) {
			m_ui->lineEditStationName->setText( query2.value(0).toString() );
			m_ui->lineEditStationGenre->setText( query2.value(1).toString() );
			m_ui->lineEditStationLanguage->setText( query2.value(2).toString() );
			m_ui->lineEditStationImage->setText( query2.value(3).toString() );
			m_ui->lineEditStationURL->setText( query2.value(4).toString() );
		}
		query2.finish();

		showStreams();
	}
}

void EditStations::streamsChanged(QTreeWidgetItem *current,QTreeWidgetItem *before)
{
	if (m_ui->treeStreams->indexOfTopLevelItem(m_ui->treeStreams->currentItem()) != -1 ) {
		qDebug() << "streamsChanged"<< m_ui->treeStreams->indexOfTopLevelItem(current) << current->data(0,Qt::UserRole).toString();

		QString sql;
		sql = QString("SELECT format, url FROM Streams WHERE id='%1'").arg( current->data(0,Qt::UserRole).toString() );
		QSqlQuery query(sql, sqldb.db);
		while (query.next()) {
			m_ui->lineEditStreamsFormat->setText( query.value(0).toString() );
			m_ui->lineEditStreamsURL->setText( query.value(1).toString() );
		}
		query.finish();
	}
}

void EditStations::clickSave()
{	
	qDebug() << "clickSave";
	qDebug() << "Stations" << m_ui->treeStations->currentItem() << m_ui->treeStations->indexOfTopLevelItem(m_ui->treeStations->currentItem());
	qDebug() << "Streams" << m_ui->treeStreams->currentItem() << m_ui->treeStreams->indexOfTopLevelItem(m_ui->treeStreams->currentItem());

	if (m_ui->treeStations->indexOfTopLevelItem(m_ui->treeStations->currentItem()) != -1 ) {
		qDebug() << "[FMtune]"<<"UPDATE Stations";
		QSqlQuery query(sqldb.db);
		query.prepare(QString("UPDATE Stations SET name = ?, genre = ?, language = ?, image = ?, url = ? WHERE id='%1'").arg( m_ui->treeStations->currentItem()->data(0,Qt::UserRole).toString() ));
		query.addBindValue(m_ui->lineEditStationName->text());
		query.addBindValue(m_ui->lineEditStationGenre->text());
		query.addBindValue(m_ui->lineEditStationLanguage->text());
		query.addBindValue(m_ui->lineEditStationImage->text());
		query.addBindValue(m_ui->lineEditStationURL->text());

		if (!query.exec()) {
			qDebug()<<"[FMtune]"<<"insert error"<<"EditStations::clickSave()"<<"UPDATE Stations";
		}
		qDebug() << "[FMtune]"<<"UPDATE Stations - COMPLETE";

		query.finish();
	}

	if (m_ui->treeStreams->indexOfTopLevelItem(m_ui->treeStreams->currentItem()) != -1 ) {
		qDebug() << "[FMtune]"<<"UPDATE Streams";
		QSqlQuery query2(sqldb.db);
		query2.prepare(QString("UPDATE Streams SET format = ?, url = ? WHERE id='%1'").arg( m_ui->treeStreams->currentItem()->data(0,Qt::UserRole).toString() ));
		query2.addBindValue(m_ui->lineEditStreamsFormat->text());
		query2.addBindValue(m_ui->lineEditStreamsURL->text());

		if (!query2.exec()) {
			qDebug()<<"[FMtune]"<<"insert error"<<"EditStations::clickSave()"<<"UPDATE Streams";
		}
		query2.finish();

		qDebug() << "[FMtune]"<<"UPDATE Streams - COMPLETE";
	}
}

void EditStations::clickStationsAdd()
{
	qDebug() << "clickStationsAdd()";

	QString sql;
	QSqlQuery query(sqldb.db);
	sql = QString("INSERT INTO Stations ([group], [name]) VALUES ('', '%1')").arg( tr("<new>") );
	if (!query.exec(sql)){
		qDebug()<<"[FMtune]"<<"insert error"<<"clickStationsAdd";
	}

	showStations();
}

void EditStations::clickStationsDelete()
{
	if (m_ui->treeStations->indexOfTopLevelItem(m_ui->treeStations->currentItem()) != -1 ) {
		qDebug() << "clickStationsDelete()";
		if ( QMessageBox::question(this, "FMtune",
									tr("Delete station?"),
									QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel,
									QMessageBox::No)	== QMessageBox::Yes ) {
			QString sql;
			QSqlQuery query(sqldb.db);
			sql = QString("DELETE FROM Stations WHERE id='%1'").arg( m_ui->treeStations->currentItem()->data(0,Qt::UserRole).toString() );
			if (!query.exec(sql)){
				qDebug()<<"[FMtune]"<<"delete error - Stations";
			}

			QSqlQuery query2(sqldb.db);
			sql = QString("DELETE FROM Streams WHERE stationid='%1'").arg( m_ui->treeStations->currentItem()->data(0,Qt::UserRole).toString() );
			if (!query2.exec(sql)){
				qDebug()<<"[FMtune]"<<"delete error - Streams";
			}

			showStations();
		}
	}
}

void EditStations::clickStreamsAdd()
{	
	if (m_ui->treeStations->indexOfTopLevelItem(m_ui->treeStations->currentItem()) != -1 ) {
		qDebug() << "clickStreamsAdd()";
		QString sql;
		QSqlQuery query(sqldb.db);
		sql = QString("INSERT INTO Streams ([stationid], [format], [url]) VALUES ('%1', '%2', '')").arg( m_ui->treeStations->currentItem()->data(0,Qt::UserRole).toString(), tr("<new>") );
		if (!query.exec(sql)){
			qDebug()<<"[FMtune]"<<"insert error"<<"clickStreamsAdd";
		}

		showStreams();
	}
}
void EditStations::clickStreamsDelete()
{
	if (m_ui->treeStreams->indexOfTopLevelItem(m_ui->treeStreams->currentItem()) != -1 ) {
		qDebug() << "clickStreamsDelete()";
		if ( QMessageBox::question(this, "FMtune",
									tr("Delete stream?"),
									QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel,
									QMessageBox::No)	== QMessageBox::Yes ) {
			QString sql;
			QSqlQuery query(sqldb.db);
			sql = QString("DELETE FROM Streams WHERE id='%1'").arg(  m_ui->treeStreams->currentItem()->data(0,Qt::UserRole).toString() );
			if (!query.exec(sql)){
				qDebug()<<"[FMtune]"<<"delete error - Streams";
			}

			showStreams();
		}
	}
}

void EditStations::clickStationsUp()
{
	qDebug() << "clickStationsUp()";
}

void EditStations::clickStationsDown()
{
	qDebug() << "clickStationsDown()";
}

void EditStations::clickStreamsUp()
{
	qDebug() << "clickStreamsUp()";
}

void EditStations::clickStreamsDown()
{
	qDebug() << "clickStreamsDown()";
}

void EditStations::clickImport()
{
	qDebug() << "clickImport()";

	QString fileName = QFileDialog::getOpenFileName(this, tr("Import..."),
							"",
							tr("FMtune XML (*.ftx)")+"\n"+tr("All files (*.*)") );
	if ( !fileName.isEmpty() )	{
		qDebug()<<fileName;
		QXmlStreamReader xml;


		QFile file( fileName );
		if( !file.exists() ) {
			qDebug() << "The file does not exist.";
		}


		if( !file.open( QIODevice::ReadOnly | QIODevice::Text ) )
		{
			qDebug() <<  "Failed to open.";
		}

		QTextStream in(&file);

		xml.clear();
		xml.addData( in.readAll() );

		QString currentTag;
		int idStation;

		while (!xml.atEnd()) {
			xml.readNext();

			qDebug()<<xml.lineNumber();

			if (xml.isStartElement()) {
				qDebug()<<xml.name();
				if (xml.name() == "FMtuneXML") {
					qDebug()<<"FMtuneXML"<<xml.attributes().value("version").toString();
				} else if (xml.name() == "station") {

					QSqlQuery query(sqldb.db);
					query.prepare("INSERT INTO Stations ([group], [name], [genre], [language], [image], [url]) VALUES (?, ?, ?, ?, ?, ?)");
					query.addBindValue( xml.attributes().value("group").toString() );
					query.addBindValue( xml.attributes().value("name").toString() );
					query.addBindValue( xml.attributes().value("genre").toString() );
					query.addBindValue( xml.attributes().value("language").toString() );
					query.addBindValue( xml.attributes().value("image").toString() );
					query.addBindValue( xml.attributes().value("url").toString() );
					if (!query.exec()){
						qDebug()<<"[FMtune]"<<"insert error, table Stations"<<"clickImport()";
					}

					idStation = query.lastInsertId().toInt();
				} else if (xml.name() == "streams") {				
					QSqlQuery query3(sqldb.db);
					query3.prepare(QString("UPDATE Stations SET defaultstream = ? WHERE id='%1'").arg( idStation ));
					query3.addBindValue(xml.attributes().value("default").toString());

					if (!query3.exec()) {
						qDebug()<<"[FMtune]"<<"insert error"<<"clickImport()"<<"UPDATE Stations";
					}

				} else if (xml.name() == "stream") {
					QSqlQuery query2(sqldb.db);
					query2.prepare("INSERT INTO Streams ([stationid], [format], [url]) VALUES (?, ?, ?)");
					query2.addBindValue( idStation );
					query2.addBindValue( xml.attributes().value("format").toString() );
					query2.addBindValue( xml.attributes().value("url").toString() );
					if (!query2.exec()){
						qDebug()<<"[FMtune]"<<"insert error, table Streams"<<"clickImport()";
					}
				}
			}
		}
		if (xml.error() && xml.error() != QXmlStreamReader::PrematureEndOfDocumentError) {
			qWarning() << "XML ERROR: line" << xml.lineNumber() << " column " << xml.columnNumber() << ": " << xml.errorString();
		}

		file.close();
	}

	showStations();
}

void EditStations::clickExport()
{
	qDebug() << "clickExport()";

	QString fileName = QFileDialog::getSaveFileName(this, tr("Export..."),
							"",
							tr("FMtune XML (*.ftx)")+"\n"+tr("All files (*.*)") );

	if ( !fileName.isEmpty() )	{

		QFile file( fileName );
		if ( !file.open( QIODevice::WriteOnly ) )
		{
			//showMessage( QString("Failed to write to '%1'").arg(fileName) );
			qDebug()<<"Failed write";
		}

		QXmlStreamWriter stream( &file );
		stream.setAutoFormatting( true );
		stream.setAutoFormattingIndent(-1);
		stream.writeStartDocument();


		stream.writeStartElement( "FMtuneXML" );
			stream.writeAttribute( "version", "1.0" );

		QString sql;
		sql = "SELECT [id], [group], [name], [genre], [language], [image], [url], [defaultstream] FROM Stations";
		QSqlQuery query(sql, sqldb.db);
		while (query.next()) {
			stream.writeStartElement( "station" );
			//>>
			stream.writeAttribute( "group", query.value(1).toString() );
			stream.writeAttribute( "name", query.value(2).toString() );
			stream.writeAttribute( "genre", query.value(3).toString() );
			stream.writeAttribute( "language", query.value(4).toString() );
			stream.writeAttribute( "image", query.value(5).toString() );
			stream.writeAttribute( "url", query.value(6).toString() );
			stream.writeStartElement( "streams" );
			//>>
			stream.writeAttribute( "default", query.value(7).toString() );

			QString sql2;
			sql2 = QString("SELECT [id], [format], [url] FROM Streams WHERE stationid='%1'").arg( query.value(0).toString() );
			QSqlQuery query2(sql2, sqldb.db);
			while (query2.next()) {
				stream.writeStartElement( "stream" );
				//>>
				stream.writeAttribute( "format", query2.value(1).toString() );
				stream.writeAttribute( "url", query2.value(2).toString() );
				//<<
				stream.writeEndElement();
			}
			query2.finish();

			stream.writeEndElement();
			//<<
			stream.writeEndElement();

		}
		query.finish();


		stream.writeEndElement();

		stream.writeEndDocument();


		file.close();
		//showMessage( QString("Saved to '%1'").arg(fileName) );
		qDebug()<<"c o m p l e t e";
	}

}
